package com.example.ioc.definition;

import com.example.ioc.definition.bean.RoomBean;
import com.example.ioc.definition.bean.UserBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.Configuration;

/**
 * Description 自定义bean
 *
 * @author tcwong
 * @date 2022/7/24
 * Since 1.8
 */
@Configuration
public class UserBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)configurableListableBeanFactory;
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RoomBean.class);
        builder.addPropertyReference("userBean","userBean");
        beanFactory.registerBeanDefinition("roomBean",builder.getBeanDefinition());

        AnnotatedGenericBeanDefinition definition = new AnnotatedGenericBeanDefinition(RoomBean.class);
        MutablePropertyValues propertyValues = new MutablePropertyValues();
        propertyValues.add("userBean",new UserBean());
        definition.setPropertyValues(propertyValues);

        beanFactory.registerBeanDefinition("roomBean001",definition);

    }
}
